<template>
    <div class="video-upload-view">
        <!-- 导航栏 -->
        <div class="navbar">
            <div class="navbar-back" @click="goBack">
                <i class="fas fa-arrow-left"></i>
            </div>
            <div class="navbar-title">上传视频</div>
            <div class="navbar-action"></div>
        </div>

        <!-- 上传表单 -->
        <div class="upload-container">
            <!-- 视频上传区域 -->
            <div class="upload-section">
                <div class="section-title">选择视频</div>
                <div class="video-upload-area" :class="{ 'has-video': videoFile }" @click="triggerVideoUpload">
                    <template v-if="!videoFile">
                        <i class="fas fa-cloud-upload-alt upload-icon"></i>
                        <div class="upload-text">点击上传视频</div>
                        <div class="upload-hint">支持mp4、mov等格式，最大100MB</div>
                    </template>
                    <template v-else>
                        <video v-if="videoPreview" class="video-preview" :src="videoPreview" controls @loadedmetadata="handleVideoMetadata"></video>
                        <div class="video-info">
                            <div class="video-name">{{ videoFile.name }}</div>
                            <div class="video-size">{{ formatFileSize(videoFile.size) }}</div>
                        </div>
                        <div class="remove-video" @click.stop="removeVideo">
                            <i class="fas fa-times"></i>
                        </div>
                    </template>
                </div>
                <input type="file" ref="videoInput" accept="video/*" class="hidden-input" @change="handleVideoChange">
            </div>

            <!-- 封面上传区域 -->
            <div class="upload-section">
                <div class="section-title">视频封面</div>
                <div class="cover-upload-area" :class="{ 'has-cover': coverFile }" @click="triggerCoverUpload">
                    <template v-if="!coverFile">
                        <i class="fas fa-image upload-icon"></i>
                        <div class="upload-text">点击上传封面</div>
                        <div class="upload-hint">支持jpg、png等格式，建议16:9比例</div>
                    </template>
                    <template v-else>
                        <img v-if="coverPreview" class="cover-preview" :src="coverPreview" alt="视频封面">
                        <div class="remove-cover" @click.stop="removeCover">
                            <i class="fas fa-times"></i>
                        </div>
                    </template>
                </div>
                <input type="file" ref="coverInput" accept="image/*" class="hidden-input" @change="handleCoverChange">
            </div>

            <!-- 视频信息表单 -->
            <div class="upload-section">
                <div class="section-title">视频信息</div>
                <div class="form-group">
                    <div class="form-label">标题</div>
                    <input type="text" class="form-input" placeholder="请输入视频标题（2-30字）" v-model="videoTitle"
                        maxlength="30">
                </div>

                <div class="form-group">
                    <div class="form-label">描述</div>
                    <textarea class="form-textarea" placeholder="请输入视频描述（最多200字）" v-model="videoDescription"
                        maxlength="200"></textarea>
                </div>

                <div class="form-group">
                    <div class="form-label">分类标签</div>
                    <div class="category-selector">
                        <div v-for="(tag, index) in videoTags" :key="index"
                            :class="['category-tag', { active: selectedTags.includes(tag.tagId) }]"
                            @click="toggleTag(tag.tagId)">
                            {{ tag.name }}
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="form-label">关联商品</div>
                    <div class="product-link-area" @click="showProductSelector">
                        <template v-if="!selectedProducts.length">
                            <i class="fas fa-shopping-bag"></i>
                            <span>点击关联商品（可选）</span>
                        </template>
                        <template v-else>
                            <div class="selected-products">
                                <div class="product-tag" v-for="(product, index) in selectedProducts" :key="index">
                                    {{ product.name }}
                                    <i class="fas fa-times" @click.stop="removeProduct(index)"></i>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>

        <!-- 上传按钮 -->
        <div class="action-buttons">
            <button class="upload-button" :disabled="!canSubmit || uploading" @click="submitUpload">
                <i class="fas fa-spinner fa-spin" v-if="uploading"></i>
                <span v-else>上传视频</span>
            </button>
        </div>

        <!-- 上传进度弹窗 -->
        <div class="upload-progress-modal" v-if="uploading">
            <div class="progress-container">
                <div class="progress-title">正在上传...</div>
                <div class="progress-status">{{ uploadStatus }}</div>
            </div>
        </div>

        <!-- 商品选择弹窗 -->
        <van-popup v-model:show="showProductPopup" round position="bottom" class="product-selector-popup">
            <div class="popup-header">
                <van-search v-model="searchKeyword" placeholder="搜索商品名称" @update:model-value="handleSearch"
                    class="product-search-bar" />
                <van-icon name="cross" class="popup-close" @click="closeProductSelector" />
            </div>
            <div class="popup-content">
                <van-checkbox-group v-model="tempSelectedProducts" ref="checkboxGroup">
                    <div class="product-list">
                        <div v-for="product in allProducts" :key="product.productId" class="product-item"
                            @click="toggleProductSelection(product)">
                            <van-image :src="product.mainImage" class="product-image" />
                            <div class="product-details">
                                <div class="product-name">{{ product.name }}</div>
                                <div class="product-price">¥{{ product.price }}</div>
                            </div>
                            <van-checkbox :name="product" class="product-checkbox"
                                @click.stop />
                        </div>
                    </div>
                </van-checkbox-group>
            </div>
            <div class="popup-footer">
                <div class="selected-count">已选 {{ tempSelectedProducts.length }} 件</div>
                <van-button type="primary" round class="confirm-button" @click="confirmProductSelection">完成</van-button>
            </div>
        </van-popup>
    </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { Popup as VanPopup, Checkbox as VanCheckbox, CheckboxGroup as VanCheckboxGroup, Image as VanImage, Icon as VanIcon, Button as VanButton, Search as VanSearch } from 'vant';
import api from '@/network/api'

export default {
    name: 'VideoUploadView',
    components: {
        VanPopup,
        VanCheckbox,
        VanCheckboxGroup,
        VanImage,
        VanIcon,
        VanButton,
        VanSearch,
    },
    setup() {
        const router = useRouter()

        // 表单数据
        const videoFile = ref(null)
        const coverFile = ref(null)
        const videoTitle = ref('')
        const videoDescription = ref('')
        const selectedTags = ref([])
        const selectedProducts = ref([])
        const videoDuration = ref(0)

        // 商品选择相关
        const showProductPopup = ref(false);
        const allProducts = ref([]);
        const tempSelectedProducts = ref([]);
        const searchKeyword = ref('');
        let searchTimeout = null;

        // Base64 Data
        const videoBase64 = ref(null);
        const coverBase64 = ref(null);

        // 预览数据
        const videoPreview = ref('')
        const coverPreview = ref('')

        // 上传状态
        const uploading = ref(false)
        const uploadStatus = ref('准备上传')

        // DOM引用
        const videoInput = ref(null)
        const coverInput = ref(null)

        // 视频标签数据
        const videoTags = ref([])

        // 获取视频标签
        const fetchVideoTags = async () => {
            try {
                const response = await api.getVideoTags()
                videoTags.value = response.data.filter(tag => tag.tagId !== 1)
            } catch (error) {
                console.error('获取视频标签失败:', error)
                showToast('获取标签失败，请刷新重试')
            }
        }

        const fetchProducts = async () => {
            try {
                const response = await api.getProductsList();
                if (response.data) {
                    allProducts.value = response.data.data.map(p => ({ ...p, imageUrl: p.image_url, productId: p.product_id || p.productId || p.id }));
                }
            } catch (error) {
                console.error('获取商品列表失败:', error);
                showToast('获取商品失败，请稍后重试');
            }
        };

        const fileToBase64 = (file) => new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });

        // 触发视频选择
        const triggerVideoUpload = () => {
            videoInput.value.click()
        }

        // 处理视频选择
        const handleVideoChange = async (event) => {
            const file = event.target.files[0]
            if (!file) return

            if (file.size > 100 * 1024 * 1024) {
                showToast('视频文件不能超过100MB')
                return
            }

            videoFile.value = file
            videoPreview.value = URL.createObjectURL(file)
            try {
                uploadStatus.value = '正在转换视频格式...';
                videoBase64.value = await fileToBase64(file);
                uploadStatus.value = '准备上传';
            } catch (error) {
                showToast('视频文件读取失败，请重试');
                console.error(error);
            }
        }

        // 移除已选视频
        const removeVideo = () => {
            videoFile.value = null
            videoPreview.value = ''
            videoInput.value.value = ''
            videoBase64.value = null;
            videoDuration.value = 0
        }

        // 触发封面选择
        const triggerCoverUpload = () => {
            coverInput.value.click()
        }

        // 处理封面选择
        const handleCoverChange = async (event) => {
            const file = event.target.files[0]
            if (!file) return

            if (file.size > 5 * 1024 * 1024) {
                showToast('封面图片不能超过5MB')
                return
            }

            coverFile.value = file
            coverPreview.value = URL.createObjectURL(file)
            try {
                coverBase64.value = await fileToBase64(file);
            } catch (error) {
                showToast('封面文件读取失败，请重试');
                console.error(error);
            }
        }

        // 移除已选封面
        const removeCover = () => {
            coverFile.value = null
            coverPreview.value = ''
            coverInput.value.value = ''
            coverBase64.value = null;
        }

        // 切换标签选择
        const toggleTag = (tag_id) => {
            const index = selectedTags.value.indexOf(tag_id)
            if (index > -1) {
                selectedTags.value.splice(index, 1)
            } else {
                selectedTags.value.push(tag_id)
            }
        }

        const handleVideoMetadata = (event) => {
            videoDuration.value = Math.round(event.target.duration);
        };

        const handleSearch = (keyword) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(async () => {
                if (keyword) {
                    try {
                        const response = await api.searchProducts(keyword);
                        if (response.data) {
                            allProducts.value = response.data.map(p => ({ ...p, imageUrl: p.image_url, productId: p.product_id || p.productId || p.id }));
                        } else {
                            allProducts.value = [];
                        }
                    } catch (error) {
                        console.error('搜索商品失败:', error);
                        showToast('搜索失败，请稍后重试');
                    }
                } else {
                    fetchProducts();
                }
            }, 300); // 300ms防抖
        };

        // 显示商品选择器
        const showProductSelector = async () => {
            searchKeyword.value = '';
            if (allProducts.value.length === 0) {
                await fetchProducts();
            } else {
                // 如果已经有数据，可能来自上次搜索，重新加载全量数据
                await fetchProducts();
            }
            tempSelectedProducts.value = [...selectedProducts.value];
            showProductPopup.value = true;
        }

        const closeProductSelector = () => {
            showProductPopup.value = false;
        };

        const toggleProductSelection = (product) => {
            const index = tempSelectedProducts.value.findIndex(p => p.productId === product.productId);
            if (index > -1) {
                tempSelectedProducts.value.splice(index, 1);
            } else {
                tempSelectedProducts.value.push(product);
            }
        };

        const confirmProductSelection = () => {
            selectedProducts.value = [...tempSelectedProducts.value];
            closeProductSelector();
        };

        // 移除已选商品
        const removeProduct = (index) => {
            selectedProducts.value.splice(index, 1)
        }

        // 格式化文件大小
        const formatFileSize = (bytes) => {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
            return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
        }

        // 判断是否可以提交
        const canSubmit = computed(() => {
            return videoBase64.value &&
                videoTitle.value.trim().length >= 2 &&
                selectedTags.value.length > 0
        })

        // 提交上传
        const submitUpload = async () => {
            if (!canSubmit.value) return

            try {
                await showDialog({
                    title: '确认上传',
                    message: '确定要上传该视频吗？上传后需要审核才能公开展示。',
                    confirmButtonText: '确认上传',
                    cancelButtonText: '取消'
                })
            } catch {
                return 
            }

            uploading.value = true
            uploadStatus.value = '正在上传...'

            try {
                const uploadData = {
                    video: videoBase64.value,
                    title: videoTitle.value,
                    description: videoDescription.value,
                    tags: selectedTags.value,
                    coverImage: coverBase64.value,
                    products: selectedProducts.value.map(p => p.productId),
                    duration: videoDuration.value
                }
                
                await api.uploadVideo(uploadData);

                uploadStatus.value = '上传完成'

                setTimeout(() => {
                    showToast('上传成功')
                    uploading.value = false;
                    router.push('/video')
                }, 500)
            } catch (error) {
                console.error('视频上传失败:', error)
                showToast('上传失败，请重试')
                uploading.value = false
            }
        }

        const checkLogin = () => {
            api.checkLogin()
                .then(res => {
                    if (res.code !== 100) {
                        router.push('/login')
                    }
                })
                .catch(err => {
                    console.error('检查登录失败:', err)
                })
        }

        // 返回上一页
        const goBack = () => {
            router.back()
        }

        onMounted(() => {
            checkLogin()
            fetchVideoTags()
        })

        return {
            videoFile,
            coverFile,
            videoTitle,
            videoDescription,
            selectedTags,   
            selectedProducts,
            videoPreview,
            coverPreview,
            uploading,
            uploadStatus,
            videoInput,
            coverInput,
            videoTags,
            canSubmit,
            triggerVideoUpload,
            handleVideoChange,
            removeVideo,
            triggerCoverUpload,
            handleCoverChange,
            removeCover,
            toggleTag,
            showProductSelector,
            removeProduct,
            formatFileSize,
            submitUpload,
            goBack,
            handleVideoMetadata,
            showProductPopup,
            allProducts,
            tempSelectedProducts,
            closeProductSelector,
            toggleProductSelection,
            confirmProductSelection,
            searchKeyword,
            handleSearch
        }
    }
}
</script>

<style scoped>
/* 导航栏样式 */
.navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: white;
    border-bottom: 1px solid #e2e8f0;
}

.navbar-back {
    font-size: 18px;
    color: #4a5568;
}

.navbar-title {
    font-size: 18px;
    font-weight: 500;
}

.navbar-action {
    width: 18px;
    /* 保持导航栏对称 */
}

/* 上传容器样式 */
.upload-container {
    padding: 15px;
    background-color: #f8fafc;
}

.upload-section {
    background-color: white;
    border-radius: 10px;
    padding: 15px;
    margin-bottom: 15px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.section-title {
    font-size: 16px;
    font-weight: 500;
    color: #2d3748;
    margin-bottom: 15px;
}

/* 视频上传区域样式 */
.video-upload-area {
    border: 2px dashed #cbd5e0;
    border-radius: 8px;
    height: 160px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s;
    position: relative;
}

.video-upload-area:hover {
    border-color: #3490dc;
}

.video-upload-area.has-video {
    border-style: solid;
    border-color: #3490dc;
    height: 200px;
}

.upload-icon {
    font-size: 32px;
    color: #a0aec0;
    margin-bottom: 10px;
}

.upload-text {
    font-size: 16px;
    color: #4a5568;
    margin-bottom: 5px;
}

.upload-hint {
    font-size: 12px;
    color: #a0aec0;
}

.hidden-input {
    display: none;
}

.video-preview {
    width: 100%;
    height: 160px;
    object-fit: contain;
    background-color: #000;
}

.video-info {
    margin-top: 10px;
    width: 100%;
    padding: 0 10px;
}

.video-name {
    font-size: 14px;
    color: #2d3748;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.video-size {
    font-size: 12px;
    color: #a0aec0;
}

.remove-video {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2;
}

/* 封面上传区域样式 */
.cover-upload-area {
    border: 2px dashed #cbd5e0;
    border-radius: 8px;
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s;
    position: relative;
}

.cover-upload-area:hover {
    border-color: #3490dc;
}

.cover-upload-area.has-cover {
    border-style: solid;
    border-color: #3490dc;
}

.cover-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 6px;
}

.remove-cover {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* 表单样式 */
.form-group {
    margin-bottom: 15px;
}

.form-label {
    font-size: 14px;
    color: #4a5568;
    margin-bottom: 5px;
}

.form-input {
    width: 100%;
    padding: 10px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    font-size: 14px;
    outline: none;
    transition: border 0.3s;
}

.form-input:focus {
    border-color: #3490dc;
}

.form-textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    font-size: 14px;
    min-height: 100px;
    resize: none;
    outline: none;
    transition: border 0.3s;
}

.form-textarea:focus {
    border-color: #3490dc;
}

/* 分类选择器样式 */
.category-selector {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.category-tag {
    padding: 6px 12px;
    background-color: #f1f5f9;
    border-radius: 20px;
    font-size: 14px;
    color: #4a5568;
    cursor: pointer;
    transition: all 0.3s;
}

.category-tag.active {
    background-color: #3490dc;
    color: white;
}

/* 商品关联区域样式 */
.product-link-area {
    padding: 12px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    display: flex;
    align-items: center;
    color: #718096;
    cursor: pointer;
}

.product-link-area i {
    margin-right: 8px;
}

.selected-products {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.product-tag {
    padding: 4px 10px;
    background-color: #edf2f7;
    border-radius: 20px;
    font-size: 12px;
    color: #4a5568;
    display: flex;
    align-items: center;
}

.product-tag i {
    margin-left: 6px;
    font-size: 10px;
}

/* 隐私设置样式 */
.privacy-option {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
}

/* 开关样式 */
.switch {
    position: relative;
    display: inline-block;
    width: 50px;
    height: 24px;
}

.switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: .4s;
}

.slider:before {
    position: absolute;
    content: "";
    height: 16px;
    width: 16px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    transition: .4s;
}

input:checked+.slider {
    background-color: #3490dc;
}

input:focus+.slider {
    box-shadow: 0 0 1px #3490dc;
}

input:checked+.slider:before {
    transform: translateX(26px);
}

.slider.round {
    border-radius: 34px;
}

.slider.round:before {
    border-radius: 50%;
}

/* 上传按钮样式 */
.action-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    background-color: white;
    box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.1);
    z-index: 10;
}

.upload-button {
    width: 100%;
    padding: 12px;
    background-color: #3490dc;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;
}

.upload-button:disabled {
    background-color: #a0aec0;
    cursor: not-allowed;
}

/* 上传进度弹窗样式 */
.upload-progress-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
}

.progress-container {
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    text-align: center;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.progress-title {
    font-size: 18px;
    margin-bottom: 15px;
}

.progress-status {
    font-size: 14px;
    color: #666;
    margin-top: 10px;
}

/* 视图容器 */
.video-upload-view {
    min-height: 100vh;
    background-color: #f8fafc;
    padding-bottom: 70px;
    /* 为底部按钮留出空间 */
}

/* 商品选择弹窗样式 */
.product-selector-popup {
    height: 70vh;
    display: flex;
    flex-direction: column;
}

.popup-header {
    display: flex;
    align-items: center;
    padding: 5px 10px;
    border-bottom: 1px solid #f0f0f0;
}

.product-search-bar {
    flex: 1;
    padding: 0;
}

.popup-title {
    font-size: 16px;
    font-weight: 500;
}

.popup-close {
    font-size: 18px;
    color: #999;
}

.popup-content {
    flex: 1;
    overflow-y: auto;
}

.product-list {
    padding: 10px 0;
}

.product-item {
    display: flex;
    align-items: center;
    padding: 10px 15px;
}

.product-image {
    width: 60px;
    height: 60px;
    margin-right: 15px;
    border-radius: 4px;
    overflow: hidden;
}

.product-details {
    flex: 1;
    min-width: 0;
}

.product-name {
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.product-price {
    font-size: 14px;
    color: #ff5000;
    margin-top: 5px;
}

.product-checkbox {
    margin-left: 15px;
}

.popup-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    border-top: 1px solid #f0f0f0;
}

.selected-count {
    font-size: 14px;
}

.confirm-button {
    width: 120px;
}
</style>